
from study.utils import rand_str
from ability.serializer.gov import GovCourseListSerializer, GovSerializer
from django.db.models import query
from ability.models import Course, Gov, GovCourse
import traceback

from rest_framework.response import Response
from ability.enums import ErrorCode
from ability.excepts import LogicException
from ability.format import CustomResponse, GetPostParaOrNone
from rest_framework import permissions, viewsets, mixins
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
import ability.permissions as pm


class GovCreate(APIView):

	def post(self, request, *args, **kwargs):
		self.response_format = CustomResponse().response
		try:
			name = GetPostParaOrNone(self.request.data, 'name')
			volume = GetPostParaOrNone(self.request.data, 'volume')
			if name is None or volume is None:
				raise LogicException('参数不正确')

			gov = Gov.getOne(name=name)
			if gov is not None:
				raise LogicException('名称已存在')

			Gov.create(name, volume)
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)

class GovUpdate(APIView):

	def post(self, request, *args, **kwargs):
		self.response_format = CustomResponse().response
		try:
			name = GetPostParaOrNone(self.request.data, 'name')
			id = self.kwargs['pk']
			if name is None:
				raise LogicException('名称不可为空')

			gov = Gov.getById(id)
			if gov is None:
				raise LogicException('数据不存在')

			gov.name = name
			gov.save()
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)


class GovDelete(APIView):

	def post(self, request, *args, **kwargs):
		self.response_format = CustomResponse().response
		try:
			gov_id = GetPostParaOrNone(self.request.data, 'gov_id')
			gov = Gov.objects.get(id=gov_id)
			gov.delete()
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.sys_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)
	
class GovList(mixins.ListModelMixin, viewsets.GenericViewSet):

	queryset = Gov.objects.all()
	permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission]
	serializer_class = GovSerializer

	def get_queryset(self):
		self.response_format = CustomResponse().response
		queryset = self.queryset.order_by('-id')
		name = self.request.query_params.get('name', None)
		if name is not None:
			queryset = queryset.filter(name=name)
		return queryset

class GovCourseCreate(GenericAPIView):

	def post(self, request, *args, **kwargs):
		self.response_format = CustomResponse().response
		try:
			gov_id = GetPostParaOrNone(self.request.data, 'gov_id')
			gov = Gov.objects.get(id=gov_id)
			if gov is None:
				raise LogicException("单位不存在")

			course_id = GetPostParaOrNone(self.request.data, 'course_id')
			course = Course.objects.get(id=course_id)
			if course is None:
				self.response_format['error_code'] = ErrorCode.comon_error.value
				self.response_format['message'] = "课程不存在"
				return Response(self.response_format)

			gov_course = GovCourse.objects.filter(gov=gov, course=course).first()
			if gov_course is not None:
				raise LogicException("该课程授权已经存在")
			gov_course = GovCourse()
			gov_course.gov = gov
			gov_course.course = course
			gov_course.save()
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.comon_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)
	
class GovCourseList(mixins.ListModelMixin, viewsets.GenericViewSet):

	queryset = GovCourse.objects.all()
	permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission]
	serializer_class = GovCourseListSerializer

	def get_queryset(self):
		self.response_format = CustomResponse().response
		queryset = self.queryset.order_by('-id')

		gov = self.request.query_params.get('gov_id', None)
		if gov is not None:
			queryset = queryset.filter(gov_id=gov)

		course = self.request.query_params.get('cource_id', None)
		if course is not None:
			queryset = queryset.filter(course_id=course)

		return queryset
 
class GovDetail(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    serializer_class = GovSerializer
    permission_classes = [pm.CustomIsAuthenticated, pm.AdminPermission]

    def __init__(self, **kwargs):
        self.response_format = CustomResponse().response
        super(GovDetail, self).__init__(**kwargs)
    
    def get_queryset(self):
      return Gov.objects

    def retrieve(self, request, *args, **kwargs):
        queryset = Gov.objects
        try:
            one = queryset.get(id = self.kwargs['pk'])
            serializer = GovSerializer(one)
            self.response_format["data"] = serializer.data
        except Gov.DoesNotExist:
            self.response_format["error_code"] = ErrorCode.parameter_error.value
            self.response_format["message"] = '数据不存在'
        
        return Response(self.response_format)
